/**
 * 段落版本对比组件
 * 支持多个AI生成版本的对比和选择
 */

import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Space, Tag, Tooltip, Radio, Slider, Badge, message } from 'antd';
import {
  SwapOutlined,
  CheckCircleOutlined,
  CopyOutlined,
  SyncOutlined,
  BarChartOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  FireOutlined,
  ThunderboltOutlined,
  FileTextOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import { ParagraphVersion, ParagraphStrategy } from '@/types/brainstorm';
import './style.css';

interface VersionComparisonProps {
  versions: ParagraphVersion[];
  selectedIndex: number;
  onSelect: (index: number) => void;
  onRegenerate?: (index: number, strategy: ParagraphStrategy) => void;
  onMerge?: (indices: number[]) => void;
}

export const VersionComparison: React.FC<VersionComparisonProps> = ({
  versions,
  selectedIndex,
  onSelect,
  onRegenerate,
  onMerge,
}) => {
  const [compareMode, setCompareMode] = useState<'side-by-side' | 'diff' | 'overlay'>('side-by-side');
  const [selectedVersions, setSelectedVersions] = useState<number[]>([0, 1]);
  const [showMetrics, setShowMetrics] = useState(true);
  const [highlightDiff, setHighlightDiff] = useState(true);

  // 获取策略图标
  const getStrategyIcon = (strategy: ParagraphStrategy) => {
    const icons: Record<ParagraphStrategy, React.ReactNode> = {
      concise: <FileTextOutlined />,
      detailed: <BulbOutlined />,
      vivid: <FireOutlined />,
      'data-driven': <BarChartOutlined />,
      mixed: <ThunderboltOutlined />,
    };
    return icons[strategy];
  };

  // 获取策略名称
  const getStrategyName = (strategy: ParagraphStrategy) => {
    const names: Record<ParagraphStrategy, string> = {
      concise: '简洁风格',
      detailed: '详细风格',
      vivid: '生动风格',
      'data-driven': '数据驱动',
      mixed: '综合风格',
    };
    return names[strategy];
  };

  // 获取策略颜色
  const getStrategyColor = (strategy: ParagraphStrategy) => {
    const colors: Record<ParagraphStrategy, string> = {
      concise: 'blue',
      detailed: 'green',
      vivid: 'orange',
      'data-driven': 'purple',
      mixed: 'cyan',
    };
    return colors[strategy];
  };

  // 计算两个版本的差异
  const calculateDiff = (text1: string, text2: string) => {
    const words1 = text1.split(/\s+/);
    const words2 = text2.split(/\s+/);

    const added = words2.filter(word => !words1.includes(word));
    const removed = words1.filter(word => !words2.includes(word));

    return {
      added: added.length,
      removed: removed.length,
      similarity: Math.round((1 - (added.length + removed.length) / (words1.length + words2.length)) * 100),
    };
  };

  // 高亮显示差异
  const highlightDifferences = (text1: string, text2: string) => {
    if (!highlightDiff) return text2;

    const words1 = text1.split(/\s+/);
    const words2 = text2.split(/\s+/);

    return words2.map((word, index) => {
      if (!words1.includes(word)) {
        return `<mark style="background-color: #52c41a20; padding: 2px;">${word}</mark>`;
      }
      return word;
    }).join(' ');
  };

  // 复制版本内容
  const copyVersion = (version: ParagraphVersion) => {
    navigator.clipboard.writeText(version.content);
    message.success('内容已复制到剪贴板');
  };

  // 渲染版本卡片
  const renderVersionCard = (version: ParagraphVersion, index: number) => {
    const isSelected = index === selectedIndex;
    const metrics = version.metrics;

    return (
      <Card
        key={index}
        className={`version-card ${isSelected ? 'selected' : ''}`}
        title={
          <Space>
            {getStrategyIcon(version.strategy)}
            <span>{getStrategyName(version.strategy)}</span>
            <Tag color={getStrategyColor(version.strategy)}>版本 {index + 1}</Tag>
            {isSelected && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
          </Space>
        }
        extra={
          <Space>
            <Tooltip title="复制">
              <Button
                type="text"
                icon={<CopyOutlined />}
                onClick={() => copyVersion(version)}
              />
            </Tooltip>
            <Tooltip title="重新生成">
              <Button
                type="text"
                icon={<SyncOutlined />}
                onClick={() => onRegenerate?.(index, version.strategy)}
                loading={version.generating}
              />
            </Tooltip>
            <Button type={isSelected ? 'primary' : 'default'} onClick={() => onSelect(index)}>
              {isSelected ? '已选择' : '选择'}
            </Button>
          </Space>
        }
      >
        {/* 内容区域 */}
        <div className="version-content">
          {version.generating ? (
            <div className="generating-placeholder">
              <SyncOutlined spin />
              <span>正在生成...</span>
            </div>
          ) : version.error ? (
            <div className="error-message">{version.error}</div>
          ) : (
            <p
              className="content-text"
              dangerouslySetInnerHTML={{
                __html: compareMode === 'diff' && selectedVersions.includes(index) && selectedVersions.length === 2
                  ? highlightDifferences(versions[selectedVersions[0]].content, version.content)
                  : version.content
              }}
            />
          )}
        </div>

        {/* 指标显示 */}
        {showMetrics && !version.generating && (
          <div className="version-metrics">
            <Row gutter={[8, 8]}>
              <Col span={12}>
                <div className="metric-item">
                  <span className="metric-label">相关性</span>
                  <Progress value={metrics.relevance} />
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-item">
                  <span className="metric-label">可读性</span>
                  <Progress value={metrics.readability} />
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-item">
                  <span className="metric-label">原创度</span>
                  <Progress value={metrics.originality} />
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-item">
                  <span className="metric-label">连贯性</span>
                  <Progress value={metrics.coherence} />
                </div>
              </Col>
            </Row>

            {/* 底部统计 */}
            <div className="version-stats">
              <Space>
                <span>字数: {version.wordCount}</span>
                <span>AI评分: <Badge count={version.aiScore} style={{ backgroundColor: '#52c41a' }} /></span>
              </Space>
            </div>
          </div>
        )}
      </Card>
    );
  };

  // 渲染对比模式选择器
  const renderCompareControls = () => (
    <Card className="compare-controls">
      <Space size="large" wrap>
        <Radio.Group value={compareMode} onChange={(e) => setCompareMode(e.target.value)}>
          <Radio.Button value="side-by-side">并排对比</Radio.Button>
          <Radio.Button value="diff">差异对比</Radio.Button>
          <Radio.Button value="overlay">叠加对比</Radio.Button>
        </Radio.Group>

        <Space>
          <Tooltip title={showMetrics ? '隐藏指标' : '显示指标'}>
            <Button
              type="text"
              icon={showMetrics ? <EyeInvisibleOutlined /> : <EyeOutlined />}
              onClick={() => setShowMetrics(!showMetrics)}
            >
              {showMetrics ? '隐藏' : '显示'}指标
            </Button>
          </Tooltip>

          {compareMode === 'diff' && (
            <Tooltip title="高亮差异">
              <Button
                type={highlightDiff ? 'primary' : 'default'}
                icon={<SwapOutlined />}
                onClick={() => setHighlightDiff(!highlightDiff)}
              >
                高亮差异
              </Button>
            </Tooltip>
          )}

          {selectedVersions.length > 1 && (
            <Button
              type="primary"
              icon={<SwapOutlined />}
              onClick={() => onMerge?.(selectedVersions)}
            >
              合并版本
            </Button>
          )}
        </Space>
      </Space>
    </Card>
  );

  return (
    <div className="version-comparison">
      {/* 控制面板 */}
      {renderCompareControls()}

      {/* 版本展示 */}
      {compareMode === 'side-by-side' ? (
        <Row gutter={[16, 16]}>
          {versions.map((version, index) => (
            <Col key={index} xs={24} lg={versions.length > 2 ? 8 : 12}>
              {renderVersionCard(version, index)}
            </Col>
          ))}
        </Row>
      ) : compareMode === 'diff' ? (
        <div className="diff-view">
          <Row gutter={16}>
            {selectedVersions.map((index) => (
              <Col key={index} span={12}>
                {renderVersionCard(versions[index], index)}
              </Col>
            ))}
          </Row>
          {selectedVersions.length === 2 && (
            <Card className="diff-stats">
              <Space>
                <span>相似度: {calculateDiff(versions[selectedVersions[0]].content, versions[selectedVersions[1]].content).similarity}%</span>
                <span>新增: +{calculateDiff(versions[selectedVersions[0]].content, versions[selectedVersions[1]].content).added} 词</span>
                <span>删除: -{calculateDiff(versions[selectedVersions[0]].content, versions[selectedVersions[1]].content).removed} 词</span>
              </Space>
            </Card>
          )}
        </div>
      ) : (
        <div className="overlay-view">
          <Slider
            min={0}
            max={versions.length - 1}
            marks={versions.reduce((acc, _, index) => ({ ...acc, [index]: `V${index + 1}` }), {})}
            value={selectedIndex}
            onChange={(value) => onSelect(value)}
          />
          {renderVersionCard(versions[selectedIndex], selectedIndex)}
        </div>
      )}
    </div>
  );
};

// 进度条组件
const Progress: React.FC<{ value: number }> = ({ value }) => (
  <div className="progress-bar">
    <div
      className="progress-fill"
      style={{
        width: `${value}%`,
        backgroundColor: value >= 80 ? '#52c41a' : value >= 60 ? '#faad14' : '#ff4d4f',
      }}
    />
    <span className="progress-value">{value}</span>
  </div>
);